<template>
  <base-window :top="top" :unique="unique" :title="title" size="small" :show.sync="visible" width="432px" @closed="closed" class="task-need-approve-dialog">
    <div class="base-modal-content">
      <p><span class="form-item-required" v-if="remarkRequired">*</span>{{$t('task.detail.components.approveDesc')}}：</p>
      <biz-at-textarea class="biz-at-textarea" ref="atTextarea" search-url="/message/user/lists" name-key="displayName" v-model="apprForm.applyRemark" :at-users.sync="atUsers" direction="bottom">
        <template slot="item" slot-scope="item">
          <img :src="head(item.user.head)">
          <span>{{item.user.displayName}}</span>
        </template>
        <textarea ref="editor" class="base-at-textarea" @input="inputContent" :placeholder="remarkPlaceholder" maxlength="500" :rows="3"></textarea>
      </biz-at-textarea>
      <!--S 审批步骤 -->
      <div class="approve-steps">
        <el-row v-if="approveLevel === 1" :type="chooseApprover ? '' : 'flex'">
          <p>{{$t('common.base.approveUser')}}：</p>
          <form-user
            v-if="chooseApprover"
            show-tag-if-sp-user
            :field="{ displayName: $t('common.base.approveUser') }"
            v-model="approver"
            :see-all-org="true"
            :placeholder="$t('task.tip.approveTip6')"
          />
          <template v-else>
            <template v-if="isOpenData && approversStaffIds.length">
              <open-data v-for="staffId in approversStaffIds" :key="staffId" type="userName" :openid="staffId"></open-data>
            </template>
            <template v-else>
              {{getApproversLabel(approversName)}}
            </template>
          </template>
        </el-row>
        <el-steps v-else direction="vertical">
          <!-- 一级审批步骤 -->
          <el-step :title="$t('event.detail.components.dialog.text34')" status="process">
            <el-row slot="description" type="flex">
              <div class="form-item-control">
                <form-user
                  v-if="chooseApprover"
                  show-tag-if-sp-user
                  :field="{ displayName: $t('event.detail.components.dialog.text33') }"
                  v-model="approver"
                  :see-all-org="true"
                  :placeholder="$t('event.detail.components.dialog.text35')"
                />
                <div v-else>
                  <label>{{$t('common.base.approveUser')}}：</label>
                  <template v-if="isOpenData && approversStaffIds && approversStaffIds.length">
                    <open-data v-for="staffId in approversStaffIds" :key="staffId" type="userName" :openid="staffId"></open-data>
                  </template>
                  <template v-else>
                    {{getApproversLabel(approversName)}}
                  </template>
                </div>
              </div>
            </el-row>
          </el-step>
          <!-- 二级以上审批步骤 -->
          <el-step v-for="(item, idx) in multiApproverSetting" :key="idx" :title="$t('common.base.approveLevel', {data1: cnNumName[idx + 2]})" status="process">
            <el-row slot="description" type="flex">
              <div class="form-item-control">
                <form-user
                  v-if="item.isOpt === 1"
                  show-tag-if-sp-user
                  :field="{ displayName: $t('common.base.approveLevelUser', {data1: cnNumName[idx + 2]}) }"
                  :value="item.approver"
                  @input="(val) => updateApprover(val, idx)"
                  :see-all-org="true"
                  :placeholder="$t('task.tip.approveTip7', {data: cnNumName[idx + 2]})"
                />
                <div v-else>
                  <label>{{$t('common.base.approveUser')}}：</label>
                  <template v-if="isOpenData && (item.approversStaffIds || item.approversStaffId)">
                    
                    <template v-if="item.approversStaffIds">
                      <open-data v-for="staffId in item.approversStaffIds.split(',')" :key="staffId" type="userName" :openid="staffId"></open-data>
                    </template>
                    <template v-else-if="item.approversStaffId">
                      <open-data v-for="staffId in item.approversStaffId.split(',')" :key="staffId" type="userName" :openid="staffId"></open-data>
                    </template>
                    
                  </template>
                  <template v-else>
                    {{getApproversLabel(item.approversName)}}
                  </template>
                </div>
              </div>
            </el-row>
          </el-step>
        </el-steps>
      </div>
      <!--E 审批步骤 -->
    </div>
    <div slot="footer" class="dialog-footer">
      <el-button @click="closed">{{$t('common.base.cancel')}}</el-button>
      <el-button type="primary" @click="submit" :disabled="pending">{{$t('common.base.submit')}}</el-button>
    </div>
  </base-window>
</template>

<script>
import { isOpenData, openAccurateTab } from '@src/util/platform'
/* api */
import * as TaskApi from '@src/api/TaskApi.ts';

import FormUser from '@src/component/form/components/FormUser/FormUser.vue';
import _ from 'lodash'
import { getOssUrl } from '@src/util/assets'
import {enCodeAtText, getReceivers} from '@src/util/atText'
import { cutAtTextContent } from 'pub-bbx-utils'
import { useTenantId, useRootUser } from '@hooks/useRootWindow.ts';
import { PageRoutesTypeEnum } from 'pub-bbx-global/pageType/dist/enum/PageRoutesEnum'
import { EventApproversLabelEnum } from '@model/enum/LabelEnum'
import i18n from '@src/locales';

const defaultAvatar = getOssUrl('/avatar.png')
const $t = i18n.t.bind(i18n);

export default {
  name: 'event-need-approve-dialog',
  props: {
    approveId: {
      type: String,
      default: '',
    },
    remarkRequired: {
      type: Boolean,
      default: false
    },
    taskId: {
      type: String,
      default: '',
    },
    eventId: {
      type: String,
      default: '',
    },
    title: {
      type: String,
      default: $t('task.tip.proposeApproveTip1'),
    },
   
    top: {
      type: Boolean,
      default: false
    },
    unique: {
      type: Boolean,
      default: true
    },
    eventNo:{
      type: String,
      default: '',
    }
  },
  data() {
    return {
      isOpenData,
      visible: false,
      pending: false,
      chooseApprover: false,
      apprForm: {},
      approver: {},
      approversName: '',
      approversStaffIds: [],
      approveLevel: 1, // 审批等级
      multiApproverSetting: [], // 多级审批（2级以上审批）

      successBc: null,
      atUsers:[]
    }
  },
  computed: {
    remarkPlaceholder() {
      return this.$t('event.detail.components.dialog.text37', {data1: this.remarkRequired ? this.$t('common.base.isArrRequire') : this.$t('common.base.isArrOptional')});
    },
    cnNumName() {
      return [
        this.$t('common.base.number0'),
        this.$t('common.base.number1'),
        this.$t('common.base.number2'),
        this.$t('common.base.number3'),
        this.$t('common.base.number4'),
        this.$t('common.base.number5'),
        this.$t('common.base.number6'),
        this.$t('common.base.number7'),
        this.$t('common.base.number8'),
        this.$t('common.base.number9')
      ];
    }
  },
  methods: {
    // 获取审批人多语言label
    getApproversLabel(name) {
      return EventApproversLabelEnum[name] || name
    },
    /**
     * 更新多级选择的审批人
     */
    updateApprover(data, idx) {
      console.log(data, idx);
      this.$set(this.multiApproverSetting, idx, {
        ...this.multiApproverSetting[idx],
        approver: data
      })
    },
    openDialog(data, successBc, allotReason) {
      if(Object.prototype.toString.call(successBc) === '[object Function]'){
        this.successBc = successBc;
      }
      // 重置
      this.approver = {};
      this.apprForm = { source: this.taskId ? 'task' : 'event' };
      this.apprForm.applyRemark = '';
      this.apprForm.params = data;
      this.chooseApprover = false;
      this.atUsers = []
      if (successBc && Object.keys(successBc).length) this.apprForm.params = {...this.apprForm.params, ...successBc}
      if (allotReason && Object.keys(allotReason).length) this.apprForm.params = {...this.apprForm.params, ...allotReason}
      if (data.isOpt == 1) {
        this.chooseApprover = true;
      } else {
        this.approversName = data.approversName;
        const approversIds = data.approversStaffIds || data.approversStaffId;
        if(approversIds) {
          this.approversStaffIds = approversIds.split(',') || [];
        }
      }

      this.approveLevel = data.level || 1;
      this.multiApproverSetting = data.multiApproverSetting ? [...data.multiApproverSetting] : [];
      this.visible = true;
    },
    submit() {
      // 审批人由发起人选择时
      if (this.chooseApprover && !this.approver.userId) return this.$platform.alert(this.$t('event.detail.components.dialog.text38', {data1: this.approveLevel > 1 ? this.$t('common.base.level1') : ''}));

      for (let i = 0; i < this.multiApproverSetting.length; i++) {
        const approve = this.multiApproverSetting[i];
        if(approve.isOpt === 1){
          if(!approve.approver) return this.$platform.alert(this.$t('task.tip.approveTip7', {data: this.cnNumName[i + 2]}));
          if(!approve.approver.userId) return this.$platform.alert(this.$t('task.tip.approveTip7', {data: this.cnNumName[i + 2]}));
        }
      }

      // 审批说明必填校验
      if (!this.apprForm.applyRemark && this.remarkRequired) return this.$platform.notification({ type: 'error', title: this.$t('task.tip.proposeApproveTip4')})

      if (this.chooseApprover) this.apprForm.params.approveId = this.approver.userId;

      // 多级审批参数
      for (let i = 0; i < this.multiApproverSetting.length; i++) {
        const approve = this.multiApproverSetting[i];
        if(this.approveLevel > 1) {
          if (approve.isOpt === 1) this.apprForm.params.multiApproverSetting[i].approveId = approve.approver.userId;
        }
      }
      this.pending = true;

      let apprForm = _.cloneDeep(this.apprForm)
      let receivers = ''
      let query = ''
      if(this.apprForm.applyRemark){
        apprForm.applyRemark = enCodeAtText(this.apprForm.applyRemark, this.atUsers);
        receivers = getReceivers(this.apprForm.applyRemark, this.atUsers)
        let queryData = {
          receivers,
          tenantId: useTenantId().value,
          content: cutAtTextContent(this.apprForm.applyRemark),
          sendUserName: useRootUser().value?.displayName,
          bizId: this.eventId,
          bizNo: this.eventNo || this.$t('event.detail.components.dialog.text36'),
          md:'event'
        };
        query = '?';
        for (let i in queryData) {
          query += `&${i}=${queryData[i]}`;
        }
      }
      

      TaskApi.applyApprove(apprForm, query).then(async res => {
        if (res.status == 0) {
          this.$message.success(this.$platform.inDingTalk ? this.$t('task.tip.proposeApproveTip5') : this.$t('task.tip.proposeApproveTip6'));
          // 为提供jsp成功回调
          this.visible = false
          if(this.successBc) return this.successBc();
          this.$emit('success')

          this.pending = false;
          let fromId = window.frameElement.getAttribute('id');
          if(this.taskId){
            // this.$platform.openTab({
            //   id: `task_view_${this.taskId}`,
            //   title: '工单详情',
            //   close: true,
            //   url: `/task/view/${this.taskId}`,
            //   fromId,
            // });
            openAccurateTab({
              type: PageRoutesTypeEnum.PageTaskView,
              key: this.taskId,
              fromId
            })
          }else{
            // this.$platform.openTab({
            //   id: `event_view_${this.eventId}`,
            //   title: '事件详情',
            //   close: true,
            //   url: `/event/view/${this.eventId}`,
            //   fromId,
            // });
            openAccurateTab({
              type: PageRoutesTypeEnum.PageEventView,
              key: this.eventId,
              fromId
            })
          }
        
        } else {
          if (res.errorCode == 1003) {
            window.location.reload();
          }

          let confirm = await this.$platform.confirm(res.message);
          if (confirm) {
            window.location.reload();
          }

          this.pending = false;
        }
      }).catch(err => {
        this.pending = false;
      })
    },
    closed() {
      this.visible = false;
      // todo 目前只针对事件
      this.$emit('closed')
    },
    head(src){
      if(!src) return defaultAvatar;
      return src;
    },
    inputContent(event){
      let value = event.target.value;
      this.apprForm.applyRemark = value;
    },

  },
  components: {
    [FormUser.name]: FormUser
  }
}
</script>

<style lang="scss">
.task-need-approve-dialog {
  .form-item {
    margin-bottom: 10px;
    align-items: baseline;
  }
  // 以下为jsp页面兼容样式
  .form-item-required {
    color: red;
  }
  .base-modal {
    .base-modal-body {
      padding: 20px;

      .base-modal-content {
        textarea {
          width: 100%;
        }

        p {
          margin-bottom: 8px;

          &.tips {
            color: #999;
            font-size: 12px;
          }

          &.base-upload-placeholder {
            margin-bottom: 0;
          }
        }

        button{
          height: 24px;
          line-height: 32px;
          width: 24px;

          padding: 0;
          margin: 0;
          outline: none;
          color: #666;
          border: none;
          background-color: transparent;
          transition: color ease .15s;

          i {
            font-size: 14px;
          }

          &:hover{
            color: #e84040;
          }
        }
      }

      .el-button {
        min-width: auto;
        max-width: auto;
      }
    }

    .base-modal-footer {
      text-align: right;
    }

    .task-back-dialog {
      p {
        font-size: 12px;
      }
    }
  }
}

</style>

<style lang="scss" scoped>
.approve-steps{
  margin-top: 20px;
}

// elemeny-ui
::v-deep .el-step__description{
  padding: 0;
}

::v-deep .el-steps, .el-step{
  width: auto !important;
}

::v-deep .el-step__head.is-process{
  color: #BFBFBF;
  border-color: #BFBFBF;
}

textarea {
  width: 100%;
}
</style>
